package com.sergio.accounting.controller;

import com.sergio.accounting.dto.ApiResponse;
import com.sergio.accounting.dto.FileUploadResponse;
import com.sergio.accounting.service.FileUploadService;
import com.sergio.accounting.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import com.sergio.accounting.service.UserService;
import com.sergio.accounting.dto.UserProfileUpdateRequest;

@Slf4j
@RestController
@RequestMapping("/file")
@RequiredArgsConstructor
public class FileUploadController {

    private final FileUploadService fileUploadService;
    private final JwtUtil jwtUtil;
    private final UserService userService;

    /**
     * 上传头像
     */
    @PostMapping("/upload/avatar")
    public ResponseEntity<ApiResponse<FileUploadResponse>> uploadAvatar(
            @RequestParam("file") MultipartFile file,
            HttpServletRequest request) {
        
        try {
            // 从JWT token中获取用户ID
            String token = extractTokenFromRequest(request);
            if (token == null) {
                return ResponseEntity.badRequest()
                        .body(ApiResponse.error("未提供有效的认证token"));
            }

            Long userId = jwtUtil.extractUserId(token);
            if (userId == null) {
                return ResponseEntity.badRequest()
                        .body(ApiResponse.error("无效的认证token"));
            }

            // 上传头像
            FileUploadResponse response = fileUploadService.uploadAvatar(file, userId);
            
            if (response.isSuccess()) {
                // 更新用户头像URL到数据库
                UserProfileUpdateRequest userProfileUpdateRequest = new UserProfileUpdateRequest();
                userProfileUpdateRequest.setAvatarUrl(response.getFileUrl());
                // 这里只更新头像URL，其他字段保持不变
                userService.updateDetailedProfile(userId, userProfileUpdateRequest);
                
                return ResponseEntity.ok(ApiResponse.success(response));
            } else {
                return ResponseEntity.badRequest()
                        .body(ApiResponse.error(response.getMessage()));
            }

        } catch (Exception e) {
            log.error("头像上传失败", e);
            return ResponseEntity.internalServerError()
                    .body(ApiResponse.error("头像上传失败: " + e.getMessage()));
        }
    }

    /**
     * 上传其他文件
     */
    @PostMapping("/upload/other")
    public ResponseEntity<ApiResponse<FileUploadResponse>> uploadOtherFile(
            @RequestParam("file") MultipartFile file) {
        try {
            FileUploadResponse response = fileUploadService.uploadOtherFile(file);
            if (response.isSuccess()) {
                return ResponseEntity.ok(ApiResponse.success(response));
            } else {
                return ResponseEntity.badRequest()
                        .body(ApiResponse.error(response.getMessage()));
            }
        } catch (Exception e) {
            log.error("其他文件上传失败", e);
            return ResponseEntity.internalServerError()
                    .body(ApiResponse.error("其他文件上传失败: " + e.getMessage()));
        }
    }

    /**
     * 删除头像
     */
    @DeleteMapping("/delete/avatar/{fileName}")
    public ResponseEntity<ApiResponse<String>> deleteAvatar(
            @PathVariable String fileName,
            HttpServletRequest request) {
        
        try {
            // 从JWT token中获取用户ID
            String token = extractTokenFromRequest(request);
            if (token == null) {
                return ResponseEntity.badRequest()
                        .body(ApiResponse.error("未提供有效的认证token"));
            }

            Long userId = jwtUtil.extractUserId(token);
            if (userId == null) {
                return ResponseEntity.badRequest()
                        .body(ApiResponse.error("无效的认证token"));
            }

            // 删除头像文件
            boolean success = fileUploadService.deleteAvatar(fileName);
            
            if (success) {
                return ResponseEntity.ok(ApiResponse.success("头像删除成功"));
            } else {
                return ResponseEntity.badRequest()
                        .body(ApiResponse.error("头像删除失败"));
            }

        } catch (Exception e) {
            log.error("头像删除失败", e);
            return ResponseEntity.internalServerError()
                    .body(ApiResponse.error("头像删除失败: " + e.getMessage()));
        }
    }

    /**
     * 从请求中提取JWT token
     */
    private String extractTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}
